package cn.omisheep.au.core;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Properties;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
public class AuInit {

    private final AuConfig auConfig;

    private final AuKey auKey;

    public AuInit(AuConfig auConfig, @Autowired(required = false) AuKey auKey) throws SchedulerException {
        this.auConfig = auConfig;
        this.auKey = auKey;
        long l = AuUtil.parseTimeValue(auConfig.getRefreshTime());
        if (l > 0) {
            Properties properties = new Properties();
            properties.setProperty("org.quartz.threadPool.threadCount", "1");
            properties.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
            properties.setProperty("org.quartz.scheduler.instanceName", "AuScheduler");
            properties.setProperty("org.quartz.threadPool.threadNamePrefix", "key-refresh");
            Scheduler scheduler = new StdSchedulerFactory(properties).getScheduler();

            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("auKey", this.auKey);
            JobDetail jobDetail = JobBuilder.newJob(KeyRefreshJob.class)
                    .setJobData(jobDataMap)
                    .withIdentity("keyRefreshJob", "au").build();

            SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
            simpleTrigger.setName("triggerAuKeyRefresh");
            simpleTrigger.setRepeatCount(-1);
            simpleTrigger.setRepeatInterval(l);

            Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("keyRefreshTrigger", "au")
                    .startNow()
                    .withSchedule(simpleTrigger.getScheduleBuilder())
                    .build();

            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        }
    }
}
